package com.community.process._1010.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.community.process._1010.common.api.CommonResult;
import com.community.process._1010.common.api.ErrEnum;
import com.community.process._1010.common.api.ErrorAssert;
import com.community.process._1010.common.utils.CommonUtils;
import com.community.process._1010.common.utils.ExternalApiUtils;
import com.community.process._1010.config.property.ProcessProperty;
import com.community.process._1010.dao.entity.ProcessUser;
import com.community.process._1010.dao.mapper.ProcessUserMapper;
import com.community.process._1010.domains.external.ExternalTokenLoginDTO;
import com.community.process._1010.domains.external.ExternalUserData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private ProcessUserMapper processUserMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        //OPTIONS请求直接放行
        if (request.getMethod().equals(HttpMethod.OPTIONS.toString())) {
            return true;
        }
        //白名单请求直接放行
        if (matchPath(ProcessProperty.ignoringUrl,requestURI)) {
            return true;
        }
        ExternalTokenLoginDTO tokenLoginDTO = CommonUtils.getExternalTokenLoginDTO(request);
        CommonResult<ExternalUserData> result = ExternalApiUtils.getSecureUserInfo(tokenLoginDTO);
        ErrorAssert.notNull(result.getData(), "用户信息获取失败");
        if (result.getCode() != 200) {
            return responseHandle(CommonResult.failed("用户信息获取失败"),response);
        }
        Long id = result.getData().getId();
        if (id == null) {
            return responseHandle(CommonResult.failed("不允许匿名登录"),response);
        }
        ExternalUserData data = result.getData();
        ProcessUser processUser = processUserMapper.selectById(data.getId());
        if(processUser == null){
            processUser = new ProcessUser();
            processUser.setId(data.getId());
            processUser.setEmail(data.getEmail());
            processUser.setPhone(data.getMobile());
            processUser.setUsername(data.getUsername());
            processUser.setPassword("");
            processUser.setName(data.getNickname());
            processUser.setImg(data.getUserAvatar());
            processUser.setWxOpenId(data.getOpenid());
            processUser.setShopId(data.getShopId());

            processUserMapper.insert(processUser);
        }else{
            if(processUser.getWxOpenId() == null){
                processUser.setWxOpenId(data.getOpenid());
                processUser.setName(data.getNickname());
                processUserMapper.updateById(processUser);
            }
        }

        // 加入全局，在其他地方通过StpUtil访问
        request.setAttribute("openid",data.getOpenid());
        request.setAttribute("userId",data.getId());
        request.setAttribute("mobile",data.getMobile());
        request.setAttribute("username",data.getUsername());
        request.setAttribute("shopId",data.getShopId());
        request.setAttribute("Authorization",tokenLoginDTO.getToken());
        request.setAttribute("Client-Type",tokenLoginDTO.getClientType());
        request.setAttribute("Platform",tokenLoginDTO.getPlatform());
        return true;
    }

    public boolean responseHandle(CommonResult<String> result, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        response.getOutputStream().write(JSON.toJSONBytes(result));
        response.getOutputStream().flush();
        response.getOutputStream().close();
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    /**
     * 请求路径匹配
     * @param allPath 所有路径
     * @param matchPath 需要匹配的路径
     * @return boolean true 匹配成功 false 匹配失败
     */
    public boolean matchPath(String[] allPath,String matchPath) {
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String path : allPath) {
            if (pathMatcher.match(path, matchPath)) {
                return true;
            }
        }
        return false;
    }
}
